import React, { Component } from 'react';
import { Row, Col, Button, Input, Select, Switch, Pagination, Icon, message} from 'antd';
import 'antd/dist/antd.css';
import "../../../node_modules/video-react/dist/video-react.css";
import { getSongPlayerTime, } from '../../api/formatData';
import { formatHotCommentPublishTime } from '../../api/formatData'
import docCookies from '../../api/docCookies';
import {
    Player,
    ControlBar,
    PlayToggle, 
    ReplayControl, 
    ForwardControl,  
    CurrentTimeDisplay,
    TimeDivider,
    PlaybackRateMenuButton,  
    VolumeMenuButton,
    LoadingSpinner
} from 'video-react';
import { getMvById, setMvComment, starMv, collectMv, sendBarrage } from '../../api';
import Header from '../../common/header'
import Footer from '../../common/footer';
import BulletScreen from './BulletScreen'
import "./index.scss"


const { Option } = Select;
const { TextArea } = Input;


class Mv extends Component {

    constructor(props){
        super(props);
        this.state = {
            inputValue: "",
            fps: 0,
            process: 0,
            selectValue: "",
            mv: {
                mvId: 0,
                mvName: "",
                time: "",
                playCount: 0,
                singer: {
                    singerId: 0,
                    singerName: ""
                },
                mvUrl: "",
                comment: [],
                commentTotal: 0,
                barrage: [
                    {
                        startTime: 5,
                        value: "第一条弹幕"
                    },
                    {
                        startTime: 7,
                        value: "第二条弹幕"
                    },
                    {
                        startTime: 9,
                        value: "第三条弹幕"
                    }
                ]
            },
            comment: "",
            secondsElapsed: 0,
            onPlay: false,
        };

        this.bullet = null;
        this.timer = null;
    }


    componentDidMount(){

        const mvId = parseInt(this.props.location.search.match(/\d+/gi).toString());
        this.csrf = localStorage.getItem("token")  || docCookies.getItem("__csrf");;


        getMvById(parseInt(mvId)).then((res) => {
            if (res.data.code === 200) {
                this.setState({
                    mv: res.data.mv
                })
            } else {
                console.log("请求错误...");
            }
        }).catch( err => {
            console.log( err )
        });

        this.bullet = new BulletScreen({
            id: 'container'
        });

    }


    componentWillUnmount() {

        clearInterval(this.interval);

    }


    handleFresh = () => {
        const mvId = parseInt(this.props.location.search.match(/\d+/gi).toString());

        getMvById(parseInt(mvId)).then((res) => {
            if (res.data.code === 200) {
                this.setState({
                    mv: res.data.mv
                })
            } else {
                console.log("请求错误...");
            }
        }).catch( err => {
            console.log( err )
        });

        this.bullet = new BulletScreen({
            id: 'container'
        });
    };

    handleStart = () => {
        this.bullet.run();
        this.bullet.push('HELLO WORLD!!!', 'color')
    };

    handleStop = () => {
        this.bullet.stop();
        for (let key in this.timerMap) {
            console.log(this.timerMap)
            clearInterval(this.timerMap[key]);
            this.timerMap[key] = null
        }
        this.setState({
            fps: 0,
            process: 0
        })
    };

    handleSend = () => {
        this.bullet.push(this.state.inputValue, 'color')
        const mvId = parseInt(this.props.location.search.match(/\d+/gi).toString());

        sendBarrage(this.state.inputValue, this.state.secondsElapsed, mvId).then((res) => {
            if (res.data.code === 200) {

            } else {

            }
        }).catch( err => {
            console.log( err )
        });

        this.setState({
            inputValue: ""
        })

    };


    handleInput = ({ target: { value } }) => {
        this.setState({ 
            inputValue: value 
        });
    };


    handleSelectChange = (value) => {
        this.setState({
            selectValue: value
        })
    };


    handleCommentClick = () => {
        const {comment, mv} = this.state;
        let userId = JSON.parse(localStorage.getItem('loginObj')).userId

        setMvComment(userId, comment, new Date().getTime(), mv.mvId).then((res)=>{
            this.handleFresh();
        });

        this.setState({
            comment: ""
        })

        this.handleFresh()

    };


    onInputChange = e => {
        this.setState({
            comment: e.target.value,
        })
    };


    starMv = () => {
        const {comment, mv} = this.state;
        let userId = JSON.parse(localStorage.getItem('loginObj')).userId

        starMv(userId, mv.mvId).then((res)=>{
            message.info('点赞成功');
        });

    }

    collectMv = () => {
        const {comment, mv} = this.state;
        let userId = JSON.parse(localStorage.getItem('loginObj')).userId

        collectMv(userId, mv.mvId).then((res)=>{
            if(res.data.code === 200){
                message.info("收藏成功~")
            }else if(res.data.code === 501){
                message.info("MV已存在,不能重复收藏嗷~")
            }else if(res.data.code === 500){
                message.info("收藏失败！")
            }
        });
    }


    onClickPlay = () => {
        const { player } = this.player.getState();

        if(this.state.onPlay) {
            clearInterval(this.timer);
            this.player.pause();
            this.handleStop();
        } else {
            this.player.play();
            this.handleStart();
            this.timer = setInterval(() => {
                this.setState({
                    secondsElapsed: this.state.secondsElapsed + 1
                })

                for(let i = 0; i < this.state.mv.barrage.length; i++) {
                    if(this.state.mv.barrage[i].startTime === this.state.secondsElapsed) {
                        if(this.state.mv.barrage[i].value!=="") {
                            this.bullet.push(this.state.mv.barrage[i].value, 'color')
                        }
                        
                    }
                }
                
            }, 1000);
        }
        this.setState({
            onPlay: !this.state.onPlay
        })
    }

    render() {

        const {mv, inputValue} = this.state;
        this.csrf = localStorage.getItem("token")  || docCookies.getItem("__csrf");;

        //渲染评论
        const renderComment =  mv.comment.length > 0
            ?
            mv.comment.map( (item,index,arr)=>{
                const str = item.content.replace(/\n/g,'<br />');
                const showBorder = index === arr.length-1 ? false : true;
                return (
                    <div className='newComment' style={{marginBottom:"25px"}}>
                        <span className='avatar' style={{backgroundImage:`url(${"http://cyq.center:8000/"+item.user.userPicUrl})`}}></span>
                        <span className='userComment'>
                            <span style={{ color:"#1679C5",fontSize:"12px" }}>{item.user.nickname}</span>
                            <span style={{ fontSize:"12px" }} dangerouslySetInnerHTML={{__html: str}}></span>
                        </span>
                        <span className='commentTime'>{formatHotCommentPublishTime(item.time)}</span>
                    </div>
                )
            })
            :
            null;


        return (
            <div style={{ minWidth:"1150px" }}>
                <div style={{ backgroundColor:"#242400",color:"#fff",marginBottom:"6vh" }}>
                    <Header />
                </div>
                <div>
                    {/* <MusicPlay /> */}
                </div>
                <div>
                    <Row>
                        <Col span={4}>

                        </Col>
                        <Col span={16}>
                            <Row>
                                <div className="song-name" style={{marginTop:"50px", fontSize:"x-large"}}>
                                    {mv.mvName}
                                </div>
                            </Row>
                            <Row>
                                <Col span={10}>
                                    <div className='song-content-singer' style={{marginTop:"20px"}}>
                                        <span style={{ fontSize:"12px" }}>歌手：</span>
                                        <span style={{marginLeft:"5px",fontSize:"12px",color:"#2273C2" }}>{mv.singer.singerName}</span>
                                    </div>
                                    <div className='song-content-belongAlbum'>
                                        <span style={{ fontSize:"12px" }}>播放次数：</span>
                                        <span style={{marginLeft:"5px",fontSize:"12px",color:"#2273C2" }}>{mv.playCount}</span>
                                    </div>
                                    <div className='song-content-label'>
                                        <span style={{ fontSize:"12px" }}>时长：</span>
                                        <span style={{ marginLeft:"5px",fontSize:"12px",color:"#2273C2" }}>{getSongPlayerTime(mv.time)}</span>
                                    </div>
                                </Col>
                                <Col span={14}>
                                    <Row style={{marginTop: "65px", marginLeft:"230px"}}>
                                        <div className="commentText1" onClick={this.onClickPlay} style={{marginRight: 10}}>
                                            {
                                                this.state.onPlay 
                                                ?
                                                "暂停"
                                                :
                                                "播放"
                                            }
                                        </div>
                                        <div className="commentText1" onClick={this.starMv} style={{marginRight: 10}}>点赞</div>
                                        {
                                            this.csrf 
                                            ?
                                            <div className="commentText1" onClick={this.collectMv} style={{marginRight: 10}}>收藏</div>
                                            :
                                            null
                                        }
                                        
                                    </Row>
                                </Col>
                            </Row>

                            <Row>
                                <div style={{position:"relative", marginTop:"30px"}}>
                                    <canvas id="containers" style={{position: "absolute", top: "80px", left: "0px", zIndex:7}}></canvas>
                                    <div style={{height: 480, width:800, zIndex:-1}}>
                                        <Player
                                            src={"http://cyq.center:8000/"+mv.mvUrl}
                                            // src="https://media.w3.org/2010/05/sintel/trailer_hd.mp4"
                                            ref={player => {
                                                this.player = player
                                            }}
                                        >
                                            <LoadingSpinner />
                                            <ControlBar autoHide={false} disableDefaultControls={false}>
                                                <ReplayControl seconds={10} order={1.1} />
                                                <ForwardControl seconds={30} order={1.2} />
                                                <PlayToggle />
                                                <CurrentTimeDisplay order={4.1} />
                                                <TimeDivider order={4.2} />
                                                <PlaybackRateMenuButton rates={[5, 2, 1.5, 1, 0.5]} order={7.1} />
                                                <VolumeMenuButton />
                                            </ControlBar>
                                        </Player>
                                    </div>

                                </div>

                                <Row style={{}}>
                                    <div style={{marginLeft:"10px"}}>
                                        <Input placeholder="别看弹幕，看我" value={inputValue} onChange={this.handleInput} style={{width:650, marginRight: "10px", marginBottom:"30px"}}/>
                                        <div className="commentText1" onClick={this.handleSend}>发送</div>
                                    </div>
                                </Row>

                            </Row>


                            {
                                this.csrf
                                ?
                                <Row style={{marginTop:50}}>
                                    <div className='ownComment-header' style={{ marginTop:"40px" }}>
                                        <span
                                            style={{ color:"#4C4C4C",fontSize:"20px",marginRight:"20px" }}
                                        >
                                            评论
                                        </span>
                                        <span
                                            style={{ color:"#6F6F6F",fontSize:"14px" }} >
                                                共{mv.commentTotal}条评
                                        </span>
                                    </div>
                                </Row>
                                :
                                null
                            }

                            {
                                this.csrf
                                ?
                                <div className='ownComment-content' style={{ }}>
                                    <Row style={{ marginBottom:"10px", marginTop:"20px" }}>
                                        <Col span={22} style={{ position:"relative" }}>
                                            <TextArea rows={4} onChange={this.onInputChange} value={this.state.comment}/>
                                            <span className='circle'>&nbsp;</span>
                                            <span className='circle-mask'>&nbsp;</span>
                                        </Col>
                                    </Row>
                                    <Row style={{ marginBottom:"30px" }} gutter={10}>

                                        <Col span={1}>

                                        </Col>
                                        <Col span={1}>
                                            <span className='aite'></span>
                                        </Col>
                                        <Col span={19}></Col>
                                        <Col span={2} style={{ marginLeft:"-35px" }}>
                                            <div className="commentText" onClick={this.handleCommentClick}>评论</div>
                                        </Col>
                                    </Row>
                                </div>
                                :
                                null
                            }
    

                        </Col>
                        <Col span={4}></Col>
                    </Row>

                    {
                        this.csrf
                        ?
                        <Row style={{marginTop:"40px"}}>
                            <Col span={2}></Col>
                            <Col span={18}>
                                {
                                    mv.comment.length > 0
                                        ?
                                        <div style={{ marginLeft:"40px" }}>
                                            <div style={{paddingBottom:"20px"}}>
                                                <span style={{ color:"#000",fontSize:"12px",fontWeight:"bold" }}>评论</span>
                                                <span style={{ color:"#000",fontSize:"12px",fontWeight:"bold" }}>({mv.commentTotal})</span>
                                            </div>
                                            {
                                                renderComment
                                            }
                                        </div>
                                        :
                                        null
                                }
                            </Col>
                            <Col span={4}></Col>
                        </Row>
                        :
                        null
                    }


                </div>
                <div>
                    <Footer />
                </div>
            </div>
        )
    }
}


export default Mv;
